﻿// Gateway.Api 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
// 
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
// 
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Aurora.AI.Abstractions;
using Aurora.AI.Abstractions.Dtos;
using Aurora.AI.Abstractions.Images;
using Aurora.AI.Abstractions.ObjectModels.RequestModels;
using Aurora.AI.Abstractions.ObjectModels.ResponseModels.ImageResponseModel;
using Aurora.AI.Common.Options;
using Microsoft.Extensions.Logging;
using TencentCloud.Common;
using TencentCloud.Hunyuan.V20230901;
using TencentCloud.Hunyuan.V20230901.Models;

namespace Aurora.AI.Hunyuan.Images;

/// <summary>
/// huanyuan 文生图 服务  TextToImageLite
/// </summary>
public class HunyuanImageService(ILogger<HunyuanImageService> logger) : IAuroraAIImageService
{
    public async Task<ImageCreateResponse> CreateImage(AuroraAIImageCreateRequest imageCreate,
        AuroraAIPlatformOptions? options = null,
        CancellationToken cancellationToken = default)
    {
        ImageCreateResponse response = new ImageCreateResponse();

        var client = CreateClient(options);
        // 设置参数
        string rspImageType = "url";
        TextToImageLiteRequest request = new TextToImageLiteRequest()
        {
            Prompt = imageCreate.Prompt,
            Style = "000", //https://cloud.tencent.com/document/product/1729/108992
            Resolution = OpenAIImagesOption.Size.Replace("x",":"),
            LogoAdd = 0,
            RspImgType = rspImageType
        };
        try
        {
            var clientResult = await client.TextToImageLite(request);
            response.Results =
            [
                new ImageCreateResponse.ImageDataResult()
                {
                    Url = rspImageType.Equals("url") ? clientResult.ResultImage : "",
                    B64 = !rspImageType.Equals("url") ? clientResult.ResultImage : "",
                }
            ];
        }
        catch (TencentCloudSDKException sdkException)
        {
            logger.LogError(sdkException, "混元image生图异常");
            // 出现错误
            response.Error = new AuroraAIError()
            {
                Code = sdkException.ErrorCode,
                Message = sdkException.Message,
                Messages = new List<string>() { sdkException.Message }
            };
        }

        return response;
    }

    public async Task<ImageCreateResponse> CreateImageEdit(AuroraAIImageEditCreateRequest imageEditCreateRequest,
        AuroraAIPlatformOptions options = null,
        CancellationToken cancellationToken = default)
    {
        throw new NotImplementedException();
    }

    public async Task<ImageCreateResponse> CreateImageVariation(
        AuroraAIImageVariationCreateRequest imageEditCreateRequest,
        AuroraAIPlatformOptions options = null, CancellationToken cancellationToken = default)
    {
        throw new NotImplementedException();
    }


    /// <summary>
    /// 创建 并验证 client 
    /// </summary>
    /// <param name="options"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    private HunyuanClient CreateClient(AuroraAIPlatformOptions? options)
    {
        var keys = options!.ApiKey.Split("|");

        if (keys.Length != 2)
            throw new Exception("Key is invalid  format, expected secretId|secretKey");

        // 解析key 从options中
        var secretId = keys[0];
        var secretKey = keys[1];

        var client = HunyuanFactory.CreateClient(secretId, secretKey, region: options.Other);
        return client;
    }
}